package com.ysd.filter;


import cn.hutool.json.JSONUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName = "sessionFilter", urlPatterns = {"/*"})
public class myFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String path = req.getRequestURI();
        if (path.indexOf("/api2/") != -1) {
            path = path.replace("/api2/", "/api/");
            req.getRequestDispatcher(path).forward(servletRequest, servletResponse);
        }
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        // 如果不是80端口,需要将端口加上,如果是集群,则用Nginx的地址,同理不是80端口要加上端口
//        String []  allowDomain= {"http://localhost:8080"};
//        Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
        String originHeader = ((HttpServletRequest) req).getHeader("Origin");
        httpResponse.setHeader("Access-Control-Allow-Origin", originHeader);
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
        // 如果要把Cookie发到服务器，需要指定Access-Control-Allow-Credentials字段为true
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Expose-Headers", "*");
/*        if(path.indexOf("/oas/")!=-1){
            path = path.replace("/oas/","/api/oas/");
            req.getRequestDispatcher(path).forward(servletRequest,servletResponse);
        }*/
        filterChain.doFilter(req, httpResponse);
    }
}
